//
//  CMStepCounterHandle.swift
//  HSMainViewControllerHandler
//
//  Created by haisheng huang on 16/7/26.
//  Copyright © 2016年 haisheng huang. All rights reserved.
//

import Foundation
import CoreMotion


@available(iOS, introduced: 7.0, deprecated: 8.0, message: "Use CMPedometer instead")

@objc open class CMStepCounterHandle: NSObject {

    var stepCounter: CMStepCounter?
    
    override init() {
        stepCounter = CMStepCounter()
    }
    
    func isStepCountingAvailable() -> Bool {
       return CMStepCounter.isStepCountingAvailable()
    }
    
    func startStepCounting(_ updateOnStepCounts: NSInteger, handler: @escaping (Int, Date, NSError?) -> Void ) -> Void {
        
        let workQueue: OperationQueue = OperationQueue()
        self.stepCounter?.startStepCountingUpdates(to: workQueue, updateOn: 10, withHandler: { (numberOfSteps, timestamp, error) in
//            print("CMStepCounterHandle numberOfSteps:\(numberOfSteps), timeStamp:\(timestamp), error:\(error)")
            handler(numberOfSteps, timestamp, error as NSError?)
        })
    }
    
    func queryStepCounts(_ startDate: Date, endDate: Date, handler: @escaping (Int, NSError?) -> Void) -> Void {
        
        let workQueue: OperationQueue = OperationQueue()
//        let now = NSDate()
//        let dateFormatter = NSDateFormatter()
//        dateFormatter.dateFormat = "yyyy-MM-dd"
//        let dateString = dateFormatter.stringFromDate(now)
//        let past = dateFormatter.dateFromString(dateString)
//        print(endDate)
        self.stepCounter?.queryStepCountStarting(from: startDate, to: endDate, to: workQueue, withHandler: { (numberOfSteps, error) in
//            print("CMStepCounterHandle today total numberOfSteps: \(numberOfSteps), error:\(error)")
            handler(numberOfSteps, error as NSError?)
        })
    }
    
    func stopStepCountingUpdates() -> Void {
        if self.stepCounter != nil {
            self.stepCounter?.stopStepCountingUpdates()
        }
    }
}
